package com.twm.client;

import com.twm.boot.ServerMapper;
import com.twm.handler.UserClientHandler;
import com.twm.serializer.JSONSerializer;
import com.twm.serializer.RpcDecoder;
import com.twm.serializer.RpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RPCConsumer {
    //1、创建一个线程池对象 - 他要处理我们自定义事件
    private static final ExecutorService executorService =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());



    //2、生命一个自定义事件处理器  UserClientHandler

    //3、初始化客户端 （创建连接池， bootStrap 设置bootstrap 连接服务器）
    public static void initClient(final int port, final Map<Integer, ServerMapper> serverMapper) throws InterruptedException {
        // 初始化UserClientHandler
        UserClientHandler userClientHandler = new UserClientHandler();
        serverMapper.get(port).setUserClientHandler(userClientHandler);
        //创建连接池对象
        NioEventLoopGroup group = new NioEventLoopGroup();
        //创建客户端引导对象
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                //设置通道为Nio
                .channel(NioSocketChannel.class)
                //设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY, true)
                //监听channel， 并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //获取channelpipline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new RpcEncoder(Object.class, new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(Object.class, new JSONSerializer()));
                        //添加自定义事件处理器
                        pipeline.addLast(serverMapper.get(port).getUserClientHandler());
                    }
                });
            //连接服务器
        bootstrap.connect("127.0.0.1", port).sync();
    }

    public static Object createProxy(Class<?> serviceClass, final int port, final Map<Integer, ServerMapper> serverMapper){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] objects) throws Throwable {
                        //初始化客户端client
                        if (serverMapper.get(port).getUserClientHandler() == null){
                           initClient(port, serverMapper);
                        }
                        //设置参数UserClientHandler， 设置Param
                        Object object = objects[0];
                        UserClientHandler userClientHandler = serverMapper.get(port).getUserClientHandler();
                        userClientHandler.setParam(object);
                        //使用线程池， 开启一个县城处理call（） 写操作。 并返回结果
                        //return 结果
                        return executorService.submit(userClientHandler).get();
                    }
                }
        );
    }

    //4、 编写一个方法使用jdk动态代理创建对象
    // serviceClass 接口类型， 根据那个接口生成子类代理对象， providerParam ： "UserService#sayHello#"
   /* public static Object createProxy(Class<?> serviceClass, final String providerParam){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] objects) throws Throwable {
                        //初始化客户端client
                        if (userClientHandler == null){
                            initClient();
                        }
                        //设置参数UserClientHandler， 设置Param
                        Object object = objects[0];

                        userClientHandler.setParam((providerParam));
                        //使用线程池， 开启一个县城处理call（） 写操作。 并返回结果
                        //return 结果
                        return executorService.submit(userClientHandler).get();
                    }
                }
        );
    }*/

}
